package weather

import (
	"bytes"
	"encoding/json"
	"fmt"
	"io/ioutil"
	"net/http"

	"gitee.com/dayu1985/framework/context"
)

type WeatherService struct {
	Domain string
}

func NewWeatherService(cfg *context.Configuration) *WeatherService {
	// t := cfg.INI.MustValue("weather", "path", "")
	return &WeatherService{Domain: "https://api.dlmeasure.com/dlmeasure/weather/v1.0/query.json"}
}

type Night struct {
	Weather    string `json:"weather"`
	Templow    int    `json:"templow"`
	Img        string `json:"img"`
	Winddirect string `json:"winddirect"`
	Windpower  string `json:"windpower"`
}

type Day struct {
	Weather    string `json:"weather"`
	Temphigh   int    `json:"temphigh"`
	Img        string `json:"img"`
	Winddirect string `json:"winddirect"`
	Windpower  string `json:"windpower"`
}

type Daily struct {
	Date    string `json:"date"`
	Week    string `json:"week"`
	Sunrise string `json:"sunrise"`
	Sunset  string `json:"sunset"`
	Night   Night  `json:"night"`
	Day     Day    `json:"day"`
}

type Response struct {
	City    string  `json:"city"`
	Maxtemp int     `json:"maxtemp"`
	Temp    int     `json:"temp"`
	Ptime   string  `json:"ptime"`
	Mintemp int     `json:"mintemp"`
	Weaval  string  `json:"weaval"`
	Wd      string  `json:"wd"`
	Ws      string  `json:"ws"`
	Weather string  `json:"weather"`
	Dt      string  `json:"dt"`
	Daily   []Daily `json:"daily"`
}

type WeatherRst struct {
	Code     int      `json:"code"`
	Message  string   `json:"message"`
	Response Response `json:"response"`
}

func NewWeatherRst() *WeatherRst {
	return &WeatherRst{}
}

func (s *WeatherService) Sync(city string, withDaily bool) (rst WeatherRst, err error) {

	param := make(map[string]interface{})
	param["city"] = city
	param["withDaily"] = withDaily
	bytesData, err := json.Marshal(param)
	if err != nil {
		fmt.Println(err.Error())
		return
	}
	reader := bytes.NewReader(bytesData)
	request, err := http.NewRequest("POST", s.Domain, reader)
	if err != nil {
		fmt.Println(err.Error())
		return
	}
	request.Header.Set("Content-Type", "application/json;charset=UTF-8")
	client := http.Client{}
	resp, err := client.Do(request)
	if err != nil {
		fmt.Println(err.Error())
		return
	}
	respBytes, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		fmt.Println(err.Error())
		return
	}

	rst = WeatherRst{}
	err = json.Unmarshal(respBytes, &rst)
	if err != nil {
		fmt.Println(err.Error())
		return
	}

	return rst, err

}
